package com.qianxun.module.datasource1.common.service;

import com.qianxun.framework.common.util.AESUtil;
import com.qianxun.init.properties.SmsCodeProperties;
import com.qianxun.framework.common.util.ObjectUtil;
import com.qianxun.framework.common.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信功能服务
 * @author: huwei
 * @date:   2019/12/6 10:46
 * @version:  1.0.0
*/
@Slf4j
@Service
public class SmsCodeService {
    /**
     *     // appId
     *     static private String appId = "EUCP-EMY-SMS1-1YG0U";//
     *     // 密钥
     *     static private String secretKey = "EC626AE02771328D";//
     *     // 接口地址
     *     static private String host = "http://bjmtn.b2m.cn";// 服务地址
     *
     *     static private String smsApi = "http://bjmtn.b2m.cn/inter/sendSingleSMS";//短信发送接口
     */

    /**
     * 加密方式
     */
    private String algorithm = "AES/ECB/PKCS5Padding";
    /**
     * 编码
     */
    private String encode = "UTF-8";
    /**
     * 压缩标识
     */
    private boolean isGizp = true;

    @Resource
    private SmsCodeProperties smsCodeProperties;

    public void sendSMS(String mobile ,String smsCode) {
        log.info("---> 为".concat(mobile).concat("发送短信验证码: ").concat(smsCode));
        Map<String, Object> paramterMap = new HashMap<>(2);
        paramterMap.put("mobile", mobile);
        paramterMap.put("content", contentTemplate(smsCodeProperties.getCompany(), smsCode));
        String paramJson = ObjectUtil.toJson(paramterMap);
        log.info("---> 短信发送参数: ".concat(paramJson));
        byte[] data = paramJson.getBytes(Charset.forName("UTF-8"));
        byte[] outData = AESUtil.getInstance().encrypt(data, smsCodeProperties.getSecretKey().getBytes());
        HttpUtil.HttpResponse response = null;
        try {
            response = HttpUtil.connection(smsCodeProperties.getSmsApi()).setHeader("appId", smsCodeProperties.getAppId()).setPostParameter(outData).post();
        } catch (IOException e) {
            log.error("request sms code error ", e);
        }
        byte[] inData = AESUtil.getInstance().decrypt(response.getResponse(), smsCodeProperties.getSecretKey().getBytes());
        log.info("---> ".concat(mobile).concat("返回结果：") + new String(inData, Charset.forName("UTF-8")));
    }



    private String contentTemplate(String company, String smsCode) {
        StringBuffer sb = new StringBuffer();
        //添加公司前缀
        sb.append("【").append(company).append("】");
        //添加消息体
        sb.append("验证码").append(smsCode).append(",此验证码10分钟内有效,请勿告诉他人!");
        return sb.toString();
    }

}
